<template>
  <!--  FIXME !这里和日历的滚轮事件冲突了 滚轮会不停的触发事件!  -->
  <el-dialog :title="optTitle" v-model="visible" destroy-on-close width="680px" :close-on-click-modal="false"
    @close="close">
    <div class="container">

      <div class="layout-container" v-if="tabState === '0'">
        <el-row style="display:flex;justify-content: space-between;margin-top: 10px;">
          <div>
            <span style="font-size: 12px;margin-right: 10px;width:90px;text-align: right;"><span
                style="color: red">*</span> 管理组:</span>
            <el-cascader size="small" v-model="groupForm.parentGroup" :options="treeData" placeholder="请选择管理组"
              :props="cascaderProps" @change="selectDept" :show-all-levels="false" ref="userSelectDept">
            </el-cascader>
          </div>
        </el-row>
        <el-row style="display:flex;margin-top: 10px;">
          <div>
            <span style="font-size: 12px;margin-right: 10px;width:90px;text-align: right;"><span
                style="color: red">*</span>管理身份:</span>
            <el-select v-model="groupForm.userDeptType" placeholder="请选择身份" style="width:160px" size="small">
              <el-option v-for="item in identityOption" :key="item.id" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </div>
        </el-row>

        <el-row style="display:flex;margin-top: 10px;">
          <div>
            <span style="font-size: 12px;margin-right: 10px;width:90px;text-align: right;">管理组成员:</span>
            <el-button type="text" size="small" @click="openSelectInDept">+ 从权限组选</el-button>
            <el-button type="text" size="small" @click="inviteByPersonnel">+ 从人事架构选</el-button>
          </div>
        </el-row>

        <el-row style="display:flex;margin-top: 10px;">
          <div style="font-size: 12px;margin-left: 100px;">
            <!-- <el-tag style="margin-right: 5px;margin-bottom: 5px;" closable size="small"
                    @close="handleClosePersons(index)" v-for="(item,index) in persons" :key="item.name" effect="dark">
              {{ item.name }}
            </el-tag> -->

            <el-table :data="persons" style="width: 100%" size="small">
              <el-table-column prop="name" label="姓名" width="100" />
              <el-table-column prop="phone" label="手机号" width="100" />
              <el-table-column prop="address" label="成员身份" width="180">
                <template #default="scope">
                  <el-select v-model="scope.row.deptType" placeholder="请选择身份" style="width:160px" size="small">
                    <el-option v-for="item in identityOption" :key="item.id" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click.prevent="handleClosePersons(scope.$index)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>



          </div>
        </el-row>
        <div class="foot">
          <el-button size="small" type="primary" icon="ele-Check" @click="saveUserDept">保存</el-button>
        </div>
      </div>

      <div class="layout-container" v-if="tabState === '1'">
        <el-form :model="groupForm" :rules="rules" size="small" ref="ruleFormRef" label-width="110px">
          <el-form-item label="上级管理组:" prop="parentGroup">
            <el-cascader style="width: 300px" v-model="groupForm.parentGroup" :options="treeData" placeholder="请选择管理组"
              :props="cascaderProps" :show-all-levels="false">
            </el-cascader>
          </el-form-item>
          <el-form-item label="管理组名称:" prop="groupName">
            <el-input v-model="groupForm.groupName" placeholder="本管理组名称" style="width: 250px;"></el-input>
          </el-form-item>
          <el-form-item label="管理组权限:" prop="groupAuthority">
            <el-tree :data="menuData" default-expand-all show-checkbox node-key="id" ref="roleTree" :props="defaultProps">
            </el-tree>

          </el-form-item>
          <el-form-item label="管理组成员:" prop="groupAuthority">
            <el-row>
              <el-col :span="24">
                <el-button type="text" size="small" @click="openSelectInDept">+ 从权限组选</el-button>
                <el-button type="text" size="small" @click="inviteByPersonnel">+ 从人事架构选</el-button>
              </el-col>
              <el-col :span="24">
                <el-table :data="persons" style="width: 100%" size="small">
              <el-table-column prop="name" label="姓名" width="100" />
              <el-table-column prop="phone" label="手机号" width="100" />
              <el-table-column prop="address" label="成员身份" width="180">
                <template #default="scope">
                  <el-select v-model="scope.row.deptType" placeholder="请选择身份" style="width:160px" size="small">
                    <el-option v-for="item in identityOption" :key="item.id" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click.prevent="handleClosePersons(scope.$index)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div class="foot">
          <el-button size="small" type="primary" icon="ele-Check" @click="saveGroup(ruleFormRef)">保存</el-button>
        </div>
      </div>
    </div>
  </el-dialog>


  <!-- 从部门选择人员 start -->

  <el-dialog title="选择人员" v-model="dialogDeptVisible" width="750px" :before-close="handleRoleClose">
    <div style="display: flex;">
      <div style=" width: 500px">
        <el-table :data="treeData" row-key="id" default-expand-all size="small" table-layout="fixed" border>
          <el-table-column label="部门组名称" align="left" prop="name" width="180px">
          </el-table-column>
          <el-table-column label="成员姓名" align="left" width="200px">
            <template v-slot="{ row, column, $index }">
              <div style="flex:1;display:flex;flex-direction: column;">
                <div v-for="(user, index) in row.sysUsers" :key="user.id" style="flex: 1;height:100%">
                  <el-row class="order-row-item" style="height:100%">
                    <el-col>
                      <el-button type="text" size="small" @click="selectUser(user)">选择</el-button>
                      {{ user.nickname }}

                    </el-col>
                  </el-row>
                  <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                    v-if="index < row.sysUsers.length - 1" />
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="width:200px;margin-left: 10px">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span style="font-size: 12px;
    font-weight: bold;
    color: #909399;">已选人员</span>

            </div>
          </template>
          <el-tag v-for="p in selectPersons" :key="p.userId" class="mx-1" size="small"
            style="margin-right: 5px;margin-bottom: 5px" closable :disable-transitions="false"
            @close="handleRemovePersons(p)">
            {{ p.name }}
          </el-tag>
        </el-card>
      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="dialogDeptVisible = false">取 消</el-button>
      <el-button size="small" type="primary" @click="confirmSelectUserByDept">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 从部门选择人员 end -->


  <!-- 从人事选择人员 start -->

  <el-dialog title="选择人员" v-model="dialogOtherVisible" width="30%" :before-close="handleRoleClose">
    <el-table ref="multipleTableRef" :data="oaStaffTableData" style="width: 100%" size="small"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column property="name" label="姓名" width="120" />
      <el-table-column property="phone" label="手机号" />
    </el-table>

    <div class="page-block">
      <el-pagination v-model:currentPage="queryData.current" v-model:page-size="page" :page-sizes="[10, 20, 30, 40]"
        :small="true" :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper"
        :total="total" :hide-on-single-page="true" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="dialogOtherVisible = false">取 消</el-button>
      <el-button size="small" type="primary" @click="selectUserByOaStaff">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 从人事选择人员 end -->
</template>

<script>
import { reactive, toRefs, ref, watch, computed } from 'vue'
import { useMenuApi } from '/@/api/menu'
import { create, saveDeptUser } from "/@/api/sys/dept"
import { getPage } from "/@/api/oa/staff"
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "CreateMemberAndGroup",
  emits: ['onSubmit', 'update:dialogDrawer'],
  props: {
    dialogDrawer: {
      type: Boolean,
      default: true,
    },
    type: {
      type: String,
      default: null,
    },
    treeData: {
      type: Array,
      default: null,
    },
    optTitle: {
      type: String,
      default: '新增',
    },
    addTreeData: {
      type: Object,
      default: null,
    }
  },
  setup(props, context) {
    const { dialogDrawer, type, treeData, addTreeData } = toRefs(props)
    const treeRef = ref()
    let filterTreeText = ref('')
    const menuApi = useMenuApi()
    const roleTree = ref()
    const ruleFormRef = ref()
    const userSelectDept = ref()

    watch(filterTreeText, (newVal) => {
      treeRef.value.filter(newVal)
    })
    let visible = computed({
      get: () => {
        if (dialogDrawer.value) {
          if (type.value == null || type.value === '') {
            type.value = '0'
          }
          let nowTreeData = addTreeData.value
          state.groupForm.parentGroup = nowTreeData.id
          state.groupForm.groupName = null
          state.groupForm.groupAuthority = []
          //已存在的用户
          state.persons = []
          if (type.value === '0') {
            state.title = "添加成员"
            inintPersons(nowTreeData)

          } else {
            state.title = "新增下级管理组"
            selectRole()
          }
          state.tabState = type.value
          if (treeData.value != null) {
            state.selectedTree = []
            //这里要限制只选人员 必须遍历后添加属性 disabled:true
            state.selectedTree = treeData.value
          }
          state.notSelectedOption = treeData.value
          dialogDrawer.value = true
        }
        return dialogDrawer.value
      },
      set: val => context.emit('update:dialogDrawer', val)
    })
    const state = reactive({
      parentGroupOption: [],
      identityOption: [{
        value: '0',
        label: '普通成员'
      }, {
        value: '1',
        label: '管理员'
      }],
      selectedTree: [],//树
      selectedList: [],//已选择
      notSelectedList: [],//未选择
      notSelectedOption: [],
      title: '',
      tabState: '',
      groupForm: {
        parentGroup: "4",
        parentName: null,
        groupAuthority: [],
        userDeptType: "0"
      },
      rules: {
        groupName: [
          { required: true, message: '请输入管理组名称', trigger: 'blur' }
        ]
      },
      checkAll: false,
      isIndeterminate: true,
      addMemberState: '0',
      persons: [],
      cascaderProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true
      },

      // 选择权限菜单
      dialogRoleVisible: false,
      menuData: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      // 从原本其他组选择人员
      dialogDeptVisible: false,
      checked: false,
      // 从人事选择人员
      dialogOtherVisible: false,
      sendData: {
        name: null,
        parentId: "0",
        menuIds: null,
        sysUsers: null
      },
      queryData: {
        current: 1,
        size: 10,
        state: 4,
        phone: null,
        name: null
      },
      oaStaffTableData: [],
      total: 10,
      page: 10,
      selectPersons: [],
      multipleSelection: []
    })

    //关闭时触发
    const close = () => {
      context.emit('update:dialogDrawer', false)
    }
    //提交创建组
    const submitCreateGroup = () => {

    }
    //过滤树节点
    const filterNode = (value, data) => {
      if (!value) return true
      return data.label.includes(value)
    }
    //选择未选项权限回调
    const handleCheckedCitiesChange = (array) => {
      const checkedCount = array.length
      state.checkAll = checkedCount === state.notSelectedOption.length
      state.isIndeterminate = checkedCount > 0 && checkedCount < state.notSelectedOption.length
      //ElMessage.success("修改成功")
    }
    //处理全选事件
    const handleCheckAllChange = (val) => {
      if (val) {
        state.notSelectedList = []
        state.notSelectedOption.forEach(item => {
          state.notSelectedList.push(item.label)
        })
      } else {
        state.notSelectedList = []
      }
      state.isIndeterminate = false
    }
    //移出成员
    const removeMember = () => {

    }
    //添加成员
    const addMember = () => {

    }

    const handleClosePersons = (index) => {
      state.persons.splice(index, 1);
    }
    // 选择权限
    const selectRole = () => {
      menuApi.getMenuTrees({ nowSelectDeptId: '' }).then(res => {
        state.menuData = res.data.menus
        console.log(res.data.selectMenuIds)
      })
    }

    // 选择菜单
    const confirmRole = () => {
      state.groupForm.groupAuthority = []
      // 获取实际选中的
      let array = roleTree.value.getCheckedNodes()
      for (let r of array) {
        state.groupForm.groupAuthority.push(r.id)
      }
      // 获取半包选择，例如父级
      let array2 = roleTree.value.getHalfCheckedNodes()
      for (let r of array2) {
        state.groupForm.groupAuthority.push(r.id)
      }
    }


    const openSelectInDept = () => {
      state.selectPersons = []
      state.dialogDeptVisible = true
    }
    const selectUser = (data) => {
      let user = {
        userId: data.id,
        oaStaffId: null,
        name: data.nickname,
        phone: data.phone,
        nickname: data.nickname,
        //0是可以直接入选，1是需注册受邀请进入
        type: "0"
      }
      // 找到下标
      const index = state.selectPersons.findIndex(e => e.phone === data.phone)
      if (index > -1) {
        ElMessage.success("已选择")
        return;
      }
      //判断原本是否已存在
      const index2 = state.persons.findIndex(e => e.phone === data.phone)
      if (index2 > -1) {
        ElMessage.success("已存在当前组")
        return;
      }
      state.selectPersons.push(user)
    }

    const handleRemovePersons = (data) => {
      const index = state.selectPersons.findIndex(e => e.phone === data.phone)
      state.selectPersons.splice(index, 1);
    }

    const confirmSelectUserByDept = () => {
      state.dialogDeptVisible = false
      if (state.selectPersons.length > 0) {
        for (let sp of state.selectPersons) {
          state.persons.push(sp)
        }
      }
    }


    const saveGroup = async (formEl) => {
      if (!formEl) return
      await formEl.validate((valid) => {
        if (valid) {
          // 获取已选择权限
          confirmRole()
          // 上级ID
          if (state.groupForm.parentGroup instanceof Array) {
            state.sendData.parentId = state.groupForm.parentGroup != null ? state.groupForm.parentGroup[state.groupForm.parentGroup.length - 1] : "0"
          } else {
            state.sendData.parentId = state.groupForm.parentGroup
          }
          state.sendData.name = state.groupForm.groupName
          // 权限========
          state.sendData.menuIds = state.groupForm.groupAuthority
          // 人员========
          inintSendData(state.sendData);
          create(state.sendData).then(res => {
            if (res.code == 0) {
              ElMessage.success("添加成功")
              console.log(res)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }

    const inviteByPersonnel = () => {
      state.dialogOtherVisible = true
      state.multipleSelection = []
      state.queryData.current = 1
      getOAStaffList()
    }
    const handleSelectionChange = (val) => {
      state.multipleSelection = val
    }
    const handleSizeChange = e => {
      state.queryData.size = e
      getOAStaffList()
    }

    const handleCurrentChange = e => {
      state.queryData.current = e
      getOAStaffList()
    }
    const getOAStaffList = () => {
      getPage(state.queryData).then(res => {
        state.oaStaffTableData = res.data.records
        state.total = res.data.total
      })
    }

    const selectDept = (value) => {
      state.persons = []
      let data = userSelectDept.value.getCheckedNodes()[0].data
      inintPersons(data)
    }

    const inintPersons = (data) => {
      if (data.sysUsers != null && data.sysUsers.length > 0) {
        for (let su of data.sysUsers) {
          let user = {
            userId: su.id,
            oaStaffId: null,
            name: su.nickname,
            phone: su.phone,
            nickname: su.nickname,
            // 0是可以直接入选，1是需注册受邀请进入
            type: "0",
            deptType: su.deptType
          }
          state.persons.push(user)
        }
        // 未注册的用户
        for (let su of data.sysDeptStaffs) {
          let user = {
            userId: su.userId,
            oaStaffId: su.oaStaffId,
            name: su.name,
            phone: su.phone,
            nickname: su.name,
            // 0是可以直接入选，1是需注册受邀请进入
            type: "1",
            deptType: su.type,
          }
          state.persons.push(user)
        }

      }
    }

    const selectUserByOaStaff = () => {
      state.dialogOtherVisible = false
      if (state.multipleSelection != null && state.multipleSelection.length > 0) {
        for (let oastaff of state.multipleSelection) {
          let user = {
            userId: oastaff.userId,
            oaStaffId: oastaff.id,
            name: oastaff.name,
            phone: oastaff.phone,
            nickname: oastaff.name,
            deptType: "0",
            // 0是可以直接入选，1是需注册受邀请进入
            type: oastaff.userId != null ? "0" : "1"
          }
          //判断原本是否已存在
          const index = state.persons.findIndex(e => e.phone === user.phone)
          if (index < 0) {
            state.persons.push(user)
          }
        }
      }
    }

    const saveUserDept = () => {
      // 是否选择管理组
      if (state.groupForm.parentGroup == null || state.groupForm.parentGroup.length < 1) {
        ElMessage.error("请选择管理组")
        return;
      }
      // 是否选择管理身份
      if (state.groupForm.userDeptType == null) {
        ElMessage.error("请选择成员身份")
        return;
      }

      let sendData = {}
      if (state.groupForm.parentGroup instanceof Array) {
        sendData.id = state.groupForm.parentGroup != null ? state.groupForm.parentGroup[state.groupForm.parentGroup.length - 1] : null
      } else {
        sendData.id = state.groupForm.parentGroup
      }
      sendData.userDeptType = state.groupForm.userDeptType
      inintSendData(sendData);
      saveDeptUser(sendData).then(res => {
        if (res.code == 0) {
          ElMessage.success("添加成功")
        }
      })
    }

    const inintSendData = (sendData) => {
      //这个是不需要注册的
      let sysUsers = []
      //需要注册的
      let sysDeptStaffs = []
      for (let p of state.persons) {
        if (p.type == "0") {
          sysUsers.push({
            id: p.userId,
            nickname: p.name,
            phone: p.phone,
            deptType:p.deptType
          })
        } else {
          sysDeptStaffs.push({
            deptId: sendData.id,
            userId: p.userId,
            oaStaffId: p.oaStaffId,
            name: p.name,
            phone: p.phone,
            type:p.type
          })
        }
      }
      sendData.sysUsers = sysUsers
      sendData.sysDeptStaffs = sysDeptStaffs
    }

    return {
      ...toRefs(state),
      dialogDrawer,
      visible,
      type,
      treeData,
      treeRef,
      ruleFormRef,
      filterTreeText,
      close,
      submitCreateGroup,
      filterNode,
      handleCheckedCitiesChange,
      handleCheckAllChange,
      removeMember,
      addMember,
      handleClosePersons,
      selectRole,
      confirmRole,
      roleTree,
      openSelectInDept,
      selectUser,
      saveGroup,
      inviteByPersonnel,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      getOAStaffList,
      handleRemovePersons,
      confirmSelectUserByDept,
      selectDept,
      userSelectDept,
      selectUserByOaStaff,
      saveUserDept,
      inintPersons
    }
  }

}
</script>

<style scoped lang="scss">
.container {

  .title {
    display: flex;
    justify-content: space-evenly;

    .item {
      font-size: 15px;
      font-weight: bold;
      cursor: pointer;
    }

    .item:hover {
      color: #18a058;
    }

    .isActive {
      border-bottom: 3px solid #4aa71c;
      color: #18a058;

      @keyframes borderBottomOpen {
        0% {
          width: 13%;
        }

        25% {
          width: 26%;
        }

        50% {
          width: 39%;
        }

        75% {
          width: 52%;
        }

        100% {
          width: 65%;
        }
      }

    }

  }

  .layout-container {
    .foot {
      display: flex;
      justify-content: space-evenly;
      margin-top: 30px;
    }

    .btn-mid {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      width: 100%;
    }

    .not-select {
      width: 100%;
      height: 100%;
      padding-left: 20px;
      padding-right: 20px;

      .not-select-header {
        display: flex;
        border: 1px solid #ebeef5;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
        background-color: #f5f7fa;

        span {
          position: relative;
          top: 10px;
          left: 70px;
        }
      }

      .not-select-container {
        border-left: 1px solid #ebeef5;
        border-right: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        border-bottom-left-radius: 4px;
        border-bottom-right-radius: 4px;
        overflow: auto;
        max-height: 300px;

        .not-select-item {
          width: 140px;
          padding-left: 20px;
        }
      }
    }

    .member-container {
      width: 100%;
      height: 100%;
      padding-left: 20px;
      padding-right: 20px;

      .member-container-header {
        display: flex;
        height: 40px;
        border: 1px solid #ebeef5;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
        background-color: #f5f7fa;

        .select {
          width: 100%;
          height: 24px;
          padding-left: 20px;
          padding-right: 20px;
          margin-top: 6px;
        }
      }

      .member-container-selected {
        border-left: 1px solid #ebeef5;
        border-right: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        border-bottom-left-radius: 4px;
        border-bottom-right-radius: 4px;
        overflow: auto;
        max-height: 300px;
      }
    }

    .btn-container {
      width: 100%;
      height: auto;
      max-height: 340px;
    }

  }
}

.dialog-footer {
  margin-top: 10px;
  margin-left: 125px;
}
</style>
